<?php

require_once dirname(__FILE__) . '/model/service/UserAgentService.php';
require_once dirname(__FILE__) . '/model/service/WebTrafficService.php';
require_once dirname(__FILE__) . '/model/domain/Report.php';
require_once dirname(__FILE__) . '/model/domain/HttpRequest.php';
require_once dirname(__FILE__) . '/model/util/Assert.php';

	$ua = new UserAgentService();
	$date_start = ( Assert::notEmptyOrWhitespace($_REQUEST["dp-hidden-start"]) ) ? strtotime($_REQUEST["dp-hidden-start"]) : strtotime("-7 day");
	$date_end = ( Assert::notEmptyOrWhitespace($_REQUEST["dp-hidden-end"]) ) ? strtotime($_REQUEST["dp-hidden-end"]) : strtotime("now");
	
	$mongo_date_start  = new MongoDate($date_start);
	$mongo_date_end = new MongoDate($date_end);
	$visits = $ua->getUniqueVisitsPerDay($mongo_date_start, $mongo_date_end);
	$pageviews = $ua->getPageViews($mongo_date_start, $mongo_date_end);
	$unique_visitors = $ua->getUniqueVisitors($mongo_date_start, $mongo_date_end);
	
	function iterate($objs) {
		
		$i = 0;
		
		foreach ( $objs as $obj ) {
			$end = ( $i++ == $objs->count() ) ? "" : ",";
			printf(" [%s,%s]%s ", $obj["_id"]->sec * 1000, count($obj["value"]), $end);
		}
		
	}
	
	function getVisits($objs){
		
		$retval = 0;
		
		foreach ( $objs as $obj ) {
			$retval = $retval + count($obj["value"]);
		}
		echo $retval;
		
	}
	
?>


	<link rel="stylesheet" href="assets/css/ui-lightness/jquery-ui-1.8.custom.css" type="text/css" media="all" />
	<link rel="stylesheet" href="assets/css/trafficanalyzer/theme.css" type="text/css" media="all" />
	
	<!--[if IE]><script language="javascript" type="text/javascript" src="assets/js/excanvas.min.js"></script><![endif]-->
    <script language="javascript" type="text/javascript" src="assets/js/jquery-1.4.2.min.js"></script>
    <script language="javascript" type="text/javascript" src="assets/js/jquery-ui-1.8.custom.min.js"></script>
	<script language="javascript" type="text/javascript" src="assets/js/jquery.flot.js"></script>
	
	
	<div id="ta">
		
		<form id="tools" method="post" action="[*id*]">
			
			<div id="dp-opener">
				<span id="dp-view-start">
					<?php echo date("d M Y", $date_start); ?>
				</span>
				 - 
				<span id="dp-view-end">
					<?php echo date("d M Y", $date_end); ?>
				</span>
			</div>
			
			<div id="dp-toggler">
				
				<div id="dp-start"></div>
				<div id="dp-end"></div>
			
		    	<div>
		    		<input id="dp-hidden-start" name="dp-hidden-start" type="hidden" value="<?php echo date("Y-m-d", $date_start);?>" />
		    		<input id="dp-hidden-end" name="dp-hidden-end" type="hidden" value="<?php echo date("Y-m-d", $date_end);?>" />
		    		<button class="submit" type="submit">Submit</button>
		    	</div>
	    	
	    	</div>
	    	
	    </form>
	    
	    <div class="clear"></div>
	    
	    <div class="module">
		    <h2>General overview</h2>
		    <table id="ta-overview">
		    	<thead>
		    		<tr>
		    			<th>Visits</th>
		    			<th>Unique visitors</th>
		    			<th>Page views</th>
		    			<th>Exploits</th>
		    			<th>Bad bots</th>
		    			<th>Banned IP addresses</th>
		    		</tr>
		    	</thead>
		    	<tbody>
		    		<tr>
		    			<td class="odd"><?php echo getVisits($visits); ?></td>
		    			<td class="even"><?php echo count($unique_visitors["values"]); ?></td>
		    			<td class="odd"><?php echo getVisits($pageviews); ?></td>
		    			<td class="even">0</td>
		    			<td class="odd">0</td>
		    			<td class="even">0</td>
		    		</tr>
		    	</tbody>
		    </table>
	    </div>
	    
	    <div class="module">
		    <h2>Visitors</h2>
		    <div class="chart-wrap">
				<div id="visits" class="chart"></div>
				<div id="choices"></div>
			</div>
		</div>
	
	</div>
	<!-- 
	<p class="info"><?php //printf("<b>%s</b> absolute unique visitors between %s - %s.", count($unique_visitors["values"]), date("Y-m-d", $date_start), date("Y-m-d", $date_end) );?></p>  
 	-->
 
	<script type="text/javascript">
		
		$(document).ready(function() {
	
			$("#dp-toggler").hide();
			$("#dp-opener").click( function() {
			    $("#dp-toggler").toggle();
			    return false;
			});
					
			initDatePicker();
			
			var visits = [ <?php echo iterate($visits); ?> ];
			//var pageviews = [ <?php //echo iterate($pageviews, 1); ?> ];
			//var exploits = [ <?php //echo iterate($visits, 2.6); ?> ];
			//var badbots = [ <?php //echo iterate($pageviews, 2.6); ?> ];
			
		    var options = {
		    		series: { lines: { show: true, fill: 0.15, lineWidth: 2 }, 
	    					  points: { show: true },
	    					  shadowSize: 3 },
	    			colors: [ "#666", "#ff4400", "#0072bc" ],
		    		grid:   { show: true, color: "#333",  backgroundColor: "#fff", borderColor: "#666",
		    				  tickColor: "#ccc", aboveData: false, borderWidth: 2, hoverable: true,
		    				  autoHighlight: true, mouseActiveRadius: 30 }, 
					legend: { labelBoxBorderColor: null, position: "nw", margin: 10, backgroundColor: null,  noColumns:1
	      					},		    		
		    		xaxis:  { mode: "time", timeformat: "%d/%m", minTickSize: [1, "day"] }
		    	};
	
			var datasets = [
			       	{ data:visits, label:"Visitors" }
			       	//{ data:pageviews, label:"Pageviews" },
			       	//{ data:exploits, label:"Exploits" },
			       	//{ data:badbots, label:"Bad bots" }
			];   
	
		    var plot = $.plot($("#visits"), datasets, options);
		    
		    
		    /** TOOLTIP PART */
	
		    function showTooltip(x, y, contents) {
		        $('<div id="tooltip" class="tt">' + contents + '</div>').css( {
		            position: 'absolute', display: 'none', top: y + 5, left: x + 5
		        }).appendTo("body").fadeIn(200);
		    }
	
		    var previousPoint = null;
		    $("#visits").bind("plothover", function (event, pos, item) {
		        $("#x").text(pos.x.toFixed(2));
		        $("#y").text(pos.y.toFixed(2));
	
	            if (item) {
	                if ( previousPoint != item.datapoint ) {
	                    previousPoint = item.datapoint;
	                    $("#tooltip").remove();
	                    var x = item.datapoint[0].toFixed(0);
	                    var y = item.datapoint[1].toFixed(0);
	                    showTooltip(item.pageX, item.pageY, "<b>"+item.series.label + "</b>" + "<br/>" + y + " hits");
	                }
	            } else {
	                $("#tooltip").remove();
	                previousPoint = null;            
	            }
		        
		    });
	
		 	// insert checkboxes
		    var choiceContainer = $("#choices");
	
		    $.each(datasets, function(key, val) {
		    	choiceContainer.append('<div class="cb"><input type="checkbox" name="' + key +
		    	'" checked="checked" id="id' + key + '">' +
		    	'<label for="id' + key + '">'
		    	+ val.label + '</label>');
		    });
	
		    choiceContainer.find("input").click(plotAccordingToChoices);
	
		    function plotAccordingToChoices() {
		    	var data = [];
		    
		    	choiceContainer.find("input:checked").each(function () {
		    	var key = $(this).attr("name");
	
		    	if (key && datasets[key])
		    		data.push(datasets[key]);
		    	});
		    
			    if (data.length > 0)
			    	$.plot($("#visits"), data, options);
		    }
		    
		    plotAccordingToChoices(); 
			    
	
		});

		function initDatePicker() {

			var df = "yy-mm-dd";
			var vdf = "dd M yy";
			
			$("#dp-start").datepicker( { defaultDate: -7, dateFormat: vdf, onSelect: 
				function(dateText, inst) {
					var date = $.datepicker.parseDate(vdf, dateText);
					var formattedDate = $.datepicker.formatDate(df, date);
					$("#dp-hidden-start").val(formattedDate);
					$("#dp-view-start").html(dateText);
					return false;
				} 
			});

			$("#dp-end").datepicker( { dateFormat: vdf, onSelect: 
				function(dateText, inst) {
					var date = $.datepicker.parseDate(vdf, dateText);
					var formattedDate = $.datepicker.formatDate(df, date);
					$("#dp-hidden-end").val(formattedDate);
					$("#dp-view-end").html(dateText);
					return false;
				} 
			});
			
		}

		
	</script>
        
 